﻿using System;
using System.IO;
using System.Xml.Serialization;

namespace BrnShop.Core
{
    /// <summary>
    /// XML帮助类
    /// </summary>
    public class XMLHelper
    {
        public static void SaveToXml(string filePath, object sourceObj, string xmlRootName="")
        {
            if (!string.IsNullOrWhiteSpace(filePath) && sourceObj != null)
            {
                var type =  sourceObj.GetType();

                using (StreamWriter writer = new StreamWriter(filePath))
                {
                    System.Xml.Serialization.XmlSerializer xmlSerializer =
                        new System.Xml.Serialization.XmlSerializer(type);

                    xmlSerializer.Serialize(writer, sourceObj);
                }
            }
        }

        public static object LoadFromXml(string filePath, Type type)
        {
            object result = null;

            if (File.Exists(filePath))
            {
                using (StreamReader reader = new StreamReader(filePath))
                {
                    System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(type);
                    result = xmlSerializer.Deserialize(reader);
                }
            }

            return result;
        }

    }
}
